package cn.com.pansky.action.bank;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.pansky.payment.PayConf;
import cn.com.pansky.util.AppUtils;
import cn.com.pansky.util.DateUtil;
import cn.com.pansky.util.HttpClientUtil;
import cn.com.pansky.util.PayUtils;
import cn.com.pansky.util.RequestUtils;

import com.google.common.collect.Maps;

public class Refund extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {

		// 获取请求参数
		Map<String, String> reqMap = RequestUtils.getReqMap(request);
		reqMap.put(
				"refInfo",
				new String(reqMap.get("refInfo").getBytes("ISO8859-1"), "UTF-8"));
		reqMap.put("charset", PayConf.CHARSET);
//		reqMap.put("merReserved1", new String(reqMap.get("merReserved1")
//				.getBytes("ISO8859-1"), "UTF-8"));
		reqMap.put("refInfo", AppUtils.URLEncode(reqMap.get("refInfo"),
				reqMap.get("charset")));// 转换编码
//		reqMap.put(
//				"merReserved1",
//				AppUtils.URLEncode(reqMap.get("merReserved1"),
//						reqMap.get("charset")));// 转换编码
		reqMap.put("backEndUrl", "http://127.0.0.1/refundNotify");
		reqMap.put("orderCurrency", PayConf.ORDERCURRENCY);
		reqMap.put("version", PayConf.REF_PAY_VERSION);
		reqMap.put("signMethod", PayConf.SIGNMETHOD);
		reqMap.put("transType", PayConf.REF_TRANSTYPE);
		reqMap.put("merId", PayConf.MERID);
		reqMap.put("signKey", PayConf.SIGNKEY);
		reqMap.put("orderTime", DateUtil.currentTime());
		reqMap.put("orderNumber", reqMap.get("orderNumber"));
		reqMap.put("qid", reqMap.get("qid"));
		reqMap.put("refAmount", reqMap.get("refAmount"));
		reqMap.put("refInfo", reqMap.get("refInfo"));
		String[] paramKeys = new String[] { "version", "charset", "signMethod",
				"transType", "merId", "backEndUrl", "orderTime", "orderNumber",
				"qid", "refAmount", "orderCurrency", "refInfo", "merReserved1" };
		Map<String, String> paramMap = Maps.newHashMap();
		for (String item : paramKeys) {
			paramMap.put(item, reqMap.get(item));
		}

		// 生成加密签名串
		String sign = PayUtils.signDictionary(paramMap, paramKeys,
				reqMap.get("signKey"), paramMap.get("charset"));
		paramMap.put("sign", sign);
		System.out.println("向清算平台发送退款请求:" + AppUtils.restMapToStr(paramMap));
		String ret = HttpClientUtil.httpPost(PayConf.REFUND_PAY_URL, paramMap,
				paramMap.get("charset"));
		System.out.println("清算平台同步响应:" + ret);

		// 处理清算平台同步返回结果
		if (StringUtils.isNotBlank(ret)) {
			String[] retArray = ret.split("&");
			Map<String, String> retMap = Maps.newHashMap();
			for (String item : retArray) {
				String[] itemArray = item.split("=");
				retMap.put(itemArray[0], (2 == itemArray.length ? itemArray[1]
						: StringUtils.EMPTY));
			}
			String[] retKeys = new String[] { "version", "charset",
					"signMethod", "transType", "refId", "respCode", "respMsg",
					"merReserved1" };
			String retSign = PayUtils.signDictionary(retMap, retKeys,
					reqMap.get("signKey"), retMap.get("charset"));
			resp.setContentType("text/plain;charset=" + retMap.get("charset"));
			if (retSign.equals(retMap.get("sign"))) {
				System.out.println("清算平台同步响应签名验证成功");

				String respCode = retMap.get("respCode");
				String respMsg = retMap.get("respMsg");
				System.out.println("respCode=" + respCode);
				System.out.println("respMsg="
						+ AppUtils.URLDecode(respMsg, retMap.get("charset")));
				resp.getWriter().write("respCode=" + respCode);
				resp.getWriter().println();
				resp.getWriter().write(
						"respMsg="
								+ AppUtils.URLDecode(respMsg,
										retMap.get("charset")));
				resp.getWriter().println();
				// 此处添加商户业务逻辑
				if ("00".equals(respCode)) {
					System.out.println("清算平台退款请求发送成功");
					resp.getWriter().write("清算平台退款请求发送成功");
				} else {
					System.out.println("清算平台退款请求发送失败");
					resp.getWriter().write("清算平台退款请求发送失败");
				}
			} else {
				System.out.println("清算平台同步响应签名验证失败");
				resp.getWriter().write("清算平台同步响应签名验证失败");
			}
		}
	}

}
